# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


class Car():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # "User-Agent": ua.random
            # 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Cookie': 'antipas=9157lS50493330G2g77610865Z4; uuid=5841189e-079b-47c7-91d0-5fc6d709a455; cityDomain=anshan; clueSourceCode=%2A%2300; user_city_id=57; ganji_uuid=7930718040187429333023; sessionid=31f63005-18cc-4d04-c13a-367efb754165; lg=1; close_finance_popup=2020-05-04; cainfo=%7B%22ca_a%22%3A%22-%22%2C%22ca_b%22%3A%22-%22%2C%22ca_s%22%3A%22self%22%2C%22ca_n%22%3A%22self%22%2C%22ca_medium%22%3A%22-%22%2C%22ca_term%22%3A%22-%22%2C%22ca_content%22%3A%22-%22%2C%22ca_campaign%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22scode%22%3A%22-%22%2C%22keyword%22%3A%22-%22%2C%22ca_keywordid%22%3A%22-%22%2C%22display_finance_flag%22%3A%22-%22%2C%22platform%22%3A%221%22%2C%22version%22%3A1%2C%22client_ab%22%3A%22-%22%2C%22guid%22%3A%225841189e-079b-47c7-91d0-5fc6d709a455%22%2C%22ca_city%22%3A%22anshan%22%2C%22sessionid%22%3A%2231f63005-18cc-4d04-c13a-367efb754165%22%7D; _gl_tracker=%7B%22ca_source%22%3A%22-%22%2C%22ca_name%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_id%22%3A%22-%22%2C%22ca_s%22%3A%22self%22%2C%22ca_n%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22sid%22%3A79926044464%7D; preTime=%7B%22last%22%3A1588601692%2C%22this%22%3A1588601516%2C%22pre%22%3A1588601516%7D',
            'DNT': '1',
            'Host': 'www.guazi.com',
            'Referer': 'https://www.guazi.com/anshan/buy/o1/',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-User': '?1',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'
        }


    def get_contents(self, cursor):
        postData = {

        }
        url = f"https://www.guazi.com/anshan/buy/o{i}"
        html = HttpUtils.do_request("GET", url, self.headers, "")
        root = etree.HTML(html.text)
        for d in root.xpath('//ul[@class="carlist clearfix js-top"]/li'):
            dict_data = dict()
            dict_data['title'] = d.xpath('./a/h2/text()')[0]  # 标题
            dict_data['year'] = d.xpath('./a/div[1]/text()')[0]  # 年份
            dict_data['gl'] = d.xpath('./a/div[1]/text()')[1]  # 公里
            dict_data['fw'] = d.xpath('./a/div[1]/text()')[2]  # 服务
            dict_data['price'] = "".join(d.xpath('./a/div[@class="t-price"]/p//text()')).strip()  # 价格
            dict_data['price_1'] = d.xpath('./a/div[@class="t-price"]/em//text()')[0]  # 价格
            dict_data['url'] = "https://www.guazi.com" + d.xpath('./a/@href')[0]

            # 获取详细信息
            html_child = HttpUtils.do_request("GET", dict_data['url'], self.headers, "")
            root_child = etree.HTML(html_child.text)
            # 上牌时间
            dict_data['sp_time'] = root_child.xpath('//ul[@class="assort clearfix"]/li[1]/span/text()')[0]
            # 表显里程
            dict_data['gl_1'] = root_child.xpath('//ul[@class="assort clearfix"]/li[2]/span/text()')[0]
            # 排量
            dict_data['pl'] = root_child.xpath('//ul[@class="assort clearfix"]/li[3]/span/text()')[0]
            # 变速箱
            dict_data['auto'] = root_child.xpath('//ul[@class="assort clearfix"]/li[4]/span/text()')[0]
            print(str(dict_data))


if __name__ == '__main__':
    car = Car()
    for i in range(1, 51):
        print(f"============{i}=============")
        car.get_contents(i)